/*
 * @Author: ZhanXie
 * @Date: 2020-05-25 09:25:29
 * @LastEditors: ZhanXie
 * @LastEditTime: 2020-08-31 15:49:14
 * @Description: 
 * @FilePath: \next-create\server\server.js
 */ 
const Koa = require('koa')
const Router = require('koa-router')
const next = require('next') // 把next做为中间件去使用
const session = require('koa-session')
const Redis = require('ioredis')
const koaBody = require('koa-body')
const atob = require('atob')
const RedisSessionStore = require('./core/session-store')

const authRouter = require('./routers/auth')
const searchRouter = require('./routers/search')
const userRouter = require('./routers/user')

// 初始化nextjs
const dev = process.env.NODE_ENV !== 'procuction'
const app = next({ dev }) // 是否处于dev状态
const handle = app.getRequestHandler() // 处理http请求响应
global.atob = atob

// 创建redis client
const redis = new Redis()

app.prepare().then(() => {
  const server = new Koa()
  const router = new Router()

  server.keys = ['session key'] // 给 cookie 加密, 数组里面的数据依次使用
  const SESSION_CONFIG = {
    key: 'jid', // 设置到浏览器cookie的key值
    store: new RedisSessionStore(redis) // 连接数据库存取session的功能 redis
  }

  server.use(session(SESSION_CONFIG, server))

  server.use(koaBody())

  server.use(authRouter.routes(), authRouter.allowedMethods())
  server.use(userRouter.routes(), userRouter.allowedMethods())
  server.use(searchRouter.routes(), searchRouter.allowedMethods())

  
  server.use(async (ctx, next) => {
    ctx.req.session = ctx.session
    await handle(ctx.req, ctx.res)
    ctx.respond = false

    await next()
  })

  server.listen(3000, () => {
    console.log('koa server listening on 3000')
  })
}) // 等编译完再响应请求